import ipaddress
import subprocess

from lib import Config


def get_connected_ips():
    output = subprocess.check_output("netstat -ano", shell=True).decode(encoding='GBK')
    lines = output.split("\n")
    ip_map = {}
    connected_ips4 = []
    connected_ips6 = []

    for line in lines:
        if "ESTABLISHED" in line:
            parts = line.split()
            remote_ip = parts[2]
            if Config.pattern_ipv4.match(remote_ip):
                loacal_ip, l_port = parts[1].split(":")
                remote_ip, r_port = remote_ip.split(":")
                if l_port == Config.Hall_Port:
                    connected_ips4.append(remote_ip)
            elif Config.pattern_ipv6.match(remote_ip):
                print("ERROR: remote ip is IPV6", remote_ip)
                remote_ip, r_port = remote_ip.split("]:")
                remote_ip = remote_ip[1:]
                connected_ips6.append(remote_ip)

    ip_map['ipv4'] = connected_ips4
    ip_map['ipv6'] = connected_ips6
    return ip_map


def ip_to_left(ip):
    binary_ip = ''.join([bin(int(x) + 256)[3:] for x in ip.split('.')])
    num = int(binary_ip,2)
    num = num & 0xFFFFFF00
    num = num >> 8
    p = num&0xFF
    binary_ip = str(p)+ '.0'
    num = num >> 8
    p = num & 0xFF
    binary_ip = str(p) + "." + binary_ip
    num = num >> 8
    p = num & 0xFF
    binary_ip = str(p) + "." + binary_ip
    return binary_ip

def ip_to_binary(ip):
    binary_ip = ''.join([bin(int(x) + 256)[3:] for x in ip.split('.')])
    return binary_ip


def binary_to_ip(binary_ip):
    ip = '.'.join([str(int(binary_ip[i:i + 8], 2)) for i in range(0, 32, 8)])
    return ip


def calculate_subnet_mask(ip, subnet_mask):
    binary_ip = ip_to_binary(ip)
    binary_subnet_mask = ip_to_binary(subnet_mask)
    subnet_mask_binary = ''.join([str(int(binary_ip[i]) & int(binary_subnet_mask[i])) for i in range(32)])
    subnet_mask_decimal = binary_to_ip(subnet_mask_binary)
    return subnet_mask_decimal


def merge_ipv4(prefix: str, sub_ip_arr: list):
    iplist = []
    for ip in sub_ip_arr:
        iplist.append(ipaddress.IPv4Network(prefix + '.' + ip + '.0/24'))
    ips = list(ipaddress.collapse_addresses(iplist))
    ip_str = ''
    for ip in ips:
        ip_str += str(ip) + ','
    return ip_str
